package org.dream.persistence;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.dream.domain.Daydeal;
import org.dream.domain.Dealrecord;
import org.dream.domain.Industry;
import org.dream.domain.Stock;
import org.dream.dto.LongTou;
import org.dream.util.LogFactory;
import org.hibernate.Session;

/**
 * 
 * @author 关攀攀
 */
public class PersistenceServiceImpl extends BaseDAOImpl implements PersistenceService {
	IndustryPersistenceImpl industryPersistenceImpl = new IndustryPersistenceImpl();
	DealrecordPersistenceImpl dealrecordPersistenceImpl = new DealrecordPersistenceImpl();
	DaydealPersistenceImpl daydealPersistenceImpl = new DaydealPersistenceImpl();

	public Map<String, List<LongTou>> findLongTous() {
		return industryPersistenceImpl.findLongTous();
	}

	public void saveObject(Object DealRecord) {
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		session.save(DealRecord);
		session.getTransaction().commit();
	}

	public Double getDaydealPoint(String day, String code) {
		return daydealPersistenceImpl.findSZPoint(day, code);
	}

	public List<Stock> findMySelectStocks() {
		return HibernateSessionFactory.getSession().createQuery("from Stock where myflag='1'").list();

	}

	public List<Industry> findAllIndustry() {
		return HibernateSessionFactory.getSession().createQuery("from Industry order by day asc, jzf desc").list();
	}

	public List<Stock> getStocksByCode(List<String> codes) {
		StringBuffer sql = new StringBuffer("from Stock where code in('");
		for (String code : codes) {
			sql.append(code);
			sql.append("','");
		}
		sql.delete(sql.length() - 2, sql.length());
		sql.append(")");
		LogFactory.getLog().logSql(sql.toString());
		return HibernateSessionFactory.getSession().createQuery(sql.toString()).list();
	}

	public List<String> findIndustryBkmc(boolean calculate) {

		return industryPersistenceImpl.findIndustryBkmc(calculate);
	}

	public void saveDaydeals(List<Daydeal> daydeals) {
		daydealPersistenceImpl.saveDaydeals(daydeals);

	}

	public List<String> findIndustryBkmcByCal() {

		List<String> bkmcs = new ArrayList<String>();
		try {
			Statement stmt = DBUtil.getStatement();
			ResultSet rs = stmt.executeQuery("select distinct bkmc from stock");
			while (rs.next()) {
				String bkmc = rs.getString("bkmc");
				bkmcs.add(bkmc);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bkmcs;
	}

	public List<Industry> findAllIndustryByCalculate() {

		List<Industry> industries = new ArrayList<Industry>();
		try {
			Statement stmt = DBUtil.getStatement();
			ResultSet rs = stmt.executeQuery("select distinct bkmc from stock");
			while (rs.next()) {
				String bkmc = rs.getString("bkmc");
				// String
				// sql="select d.code,d.name,d.riseWidth  from daydeal d join stock s on d.code=s.code where s.bkmc='"+bkmc+"'";
				String sql = "select d.day dd,AVG(d.riseWidth) wd from daydeal d join stock s on d.code=s.code where s.bkmc='"
						+ bkmc + "' and  d.VOL!=0  group by d.day order by d.day asc";
				Statement stmt2 = DBUtil.getStatement();
				ResultSet rs2 = stmt2.executeQuery(sql);
				while (rs2.next()) {
					Industry industry = new Industry();
					industry.setDay(rs2.getString("dd"));
					industry.setJzf(rs2.getDouble("wd"));
					industry.setBkmc(bkmc);
					industries.add(industry);
				}

			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return industries;
	}

	public void saveList(List list) {
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		try {
			for (Object object : list) {
				session.save(object);
			}
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		}

	}

	public void update(Dealrecord DealRecord) {
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		session.update(DealRecord);
		session.getTransaction().commit();
	}

	public List<Dealrecord> findMoneyFlowList() {
		return HibernateSessionFactory.getSession()
				.createQuery("from DealRecord where businessName='银证转入' or businessName='银证转出'  order by HappenDate ")
				.list();
	}

	public Dealrecord get(String id) {
		return (Dealrecord) HibernateSessionFactory.getSession().get(Dealrecord.class, id);
	}

	public void removeByHql(String hql) {
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		session.createQuery(hql).executeUpdate();
		session.getTransaction().commit();
	}

	public List<Dealrecord> findByCode(String code) {
		return HibernateSessionFactory.getSession().createQuery("from DealRecord where code =:code order by day")
				.setParameter("code", code).list();
	}

	public void s(Stock stock) {
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		session.save(stock);
		session.getTransaction().commit();
	}

	public void saveStock(Stock stock) {
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		session.save(stock);
		session.getTransaction().commit();
	}

	public Stock getStockByCode(String code) {
		Session session = HibernateSessionFactory.getSession();
		return (Stock) session.createQuery("from Stock where code='" + code + "'").uniqueResult();

	}

	public List<Daydeal> findDayDealsByCode(String code) {
		return daydealPersistenceImpl.findDayDealsByCode(code);
	}


	/**
	 * 根据股票编号，开始时间，结束时间来查找股票
	 */
	public List<Daydeal> findDaydealsByCode(String code, String startdate, String enddate) {
		String hql = "from Daydeal where code =:code";
		if (startdate != null) {
			hql += " and day>='" + startdate + "' ";
		}
		if (enddate != null) {
			hql += " and day<='" + enddate + "' ";
		}

		hql += " order by day";
		return HibernateSessionFactory.getSession().createQuery(hql).setParameter("code", code).list();
	}

	private Daydeal findByDate(String code, String day) {
		return (Daydeal) HibernateSessionFactory.getSession()
				.createQuery("from Daydeal where code =:code and  day =:day").setParameter("day", day)
				.setParameter("code", code).uniqueResult();
	}

	private List<Daydeal> findByDayNum(String code, int startdaynum, int enddaynum) {
		String hql = "from Daydeal where code =:code";
		hql += " and dayNum>" + startdaynum + " ";
		hql += " and dayNum<" + enddaynum + " ";

		hql += " order by day";
		return HibernateSessionFactory.getSession().createQuery(hql).setParameter("code", code).list();
	}

	/**
	 * 得到最新的股票
	 */
	public Daydeal findRecentlyDaydeal(String code) {
		return daydealPersistenceImpl.findRecentlyDaydealMap(code);
	}

	public void saveDealRecords(List<Dealrecord> dealRecords) {
		dealrecordPersistenceImpl.saveDealRecords(dealRecords);
	}

	public List<Dealrecord> findAllDealRecord() {
		return dealrecordPersistenceImpl.findAllDealRecord();
	}

}
